package com.crlui.effect
{
	import flash.display.BitmapData;
	import flash.display.Graphics;

	/**
	 * 三解形切割工厂; 
	 * @author crl
	 * 
	 */	
	public class TrianglesFac
	{
		private var segment:int;
		internal var vertices:Vector.<Number>
		
		internal var uvtData:Vector.<Number>;
		
		internal var indices:Vector.<int>;
		
		protected var bitmapdata:BitmapData;
		
		protected var bmdW:int;
		protected var bmdH:int;
		
		public var defaultVertices:Vector.<Number>;
		
		public function TrianglesFac(bitmapData:BitmapData,segment:int=2)
		{
			this.bitmapdata=bitmapData;
			this.segment=segment;
			
			bmdH=bitmapData.height;
			bmdW=bitmapData.width
			
			var len:int=Math.pow(segment+1,2)*2;
			
			vertices=new Vector.<Number>();
			uvtData=new Vector.<Number>();
			
			indices=new Vector.<int>();
			
			
			var y:int=0;
			var x:int=0;
			
			var segmentW:int=bmdW/segment;
			var segmentH:int=bmdH/segment;
			
			var segmentT:int=segment+1;
			for(y=0;y<segmentT;y++){
				for(x=0;x<segmentT;x++){
					vertices.push(x*segmentW,y*segmentH);
					uvtData.push(x/segment,y/segment);
				}
			}
			
			var f:int;
			for(y=0;y<segment;y++){
				for(x=0;x<segment;x++){
					f=x+y*segmentT;
					indices.push(f,f+1,f+segmentT);
					indices.push(f+1,f+segmentT+1,f+segmentT);
				}
			}
			
			vertices.fixed=true;
			uvtData.fixed=true;
			indices.fixed=true;
			
			defaultVertices=vertices.concat();
			
		}
		
		public function get width():int{
			return bitmapdata.width;
		}
		
		public function get height():int{
			return bitmapdata.height;
		}
		
		
		public function draw(g:Graphics):void{
			g.clear();
			g.beginBitmapFill(bitmapdata);
			g.drawTriangles(vertices,indices,uvtData);
			g.endFill();
		}
		
		
		public function get(gx:Number,gy:Number):int{
			var x:int=Math.round(gx*segment/bmdW);
			var y:int=Math.round(gy*segment/bmdH);
			return (y*(segment+1)+x)*2;
		}
	}
}